﻿using AutoMapper;
using B.S.ProcessEgine.API.Applocations.Commands.FormDetail;
using B.S.ProcessEgine.ErrorCode;
using B.S.ProcessEgine.Infractructure.Interfaces;
using Microsoft.EntityFrameworkCore;
using MediatR;
using System.Transactions;

namespace B.S.ProcessEgine.API.Applocations.CommandHandlers.FormDetail
{
    public class FormDetailSaveCommandHandler:IRequestHandler<FormDetailSaveCommand,ApiResult>
    {
        private readonly IFormInfoDetailRepository _formDetailRepository;
        private readonly ILogger<FormDetailSaveCommandHandler> _logger;
        private readonly IMapper _mapper;

        public FormDetailSaveCommandHandler(IFormInfoDetailRepository formDetailRepository, ILogger<FormDetailSaveCommandHandler> logger, IMapper mapper)
        {
            _formDetailRepository = formDetailRepository;
            _logger = logger;
            _mapper = mapper;
        }

        public async Task<ApiResult> Handle(FormDetailSaveCommand request, CancellationToken cancellationToken)
        {
            try
            {
                //判断是否有值
                if (request.FormDetails == null || request.FormDetails.Count == 0) return ApiResult.Fail("表单详情不能为空", StateCodeEnum.Fail);

                //判断明细的值不能有空值
                var exist = request.FormDetails.Any(
                    x => string.IsNullOrEmpty(x.FieldName) || string.IsNullOrEmpty(x.FieldType) || string.IsNullOrEmpty(x.FieldDesc) || string.IsNullOrEmpty(x.FieldControl));
                if (exist)
                {
                    return ApiResult.Fail("表单详情的字段名称、字段类型、字段描述、控件类型不能为空", StateCodeEnum.Fail);
                }

                var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled);
                try
                {
                    //先删除已有的表单详情

                    //查找到当前的formid
                    var formId = request.FormDetails.Select(x => x.FormId).Distinct().FirstOrDefault();
                    //获取之前的所有表单明细
                    var formDetail = await _formDetailRepository.GetAll().Where(x => x.FormId == formId && !x.IsDel).ToListAsync(cancellationToken: cancellationToken);
                    // 将之前的表单明细标记为删除
                    foreach (var detail in formDetail) detail.IsDel = true;

                    await _formDetailRepository.UpdateRangeAsync(formDetail);

                    //新增表单明细
                    var formDetails = _mapper.Map<IList<Domain.Entities.FormInfoDetail>>(request.FormDetails);

                    foreach (var detail in formDetails) detail.FormId = formId;
                    await _formDetailRepository.AddRangeAsync(formDetails);

                    scope.Complete();
                    return ApiResult.Success(StateCodeEnum.Ok);
                }
                catch (Exception e)
                {
                    _logger.LogError(e, "FormDetailSaveCommandHandler Error");
                    return ApiResult.Fail("添加表单详情异常", StateCodeEnum.Exception);
                }
                finally
                {

                    scope.Dispose();
                }
            }
            catch (Exception e)
            {
                _logger.LogError(e, "FormDetailSaveCommandHandler Error");
                return ApiResult.Fail("添加表单详情异常", StateCodeEnum.Exception);
            }
        }
    }
}
